<template>
  <div class="user-activity-management">
    <!-- 搜索筛选区域 -->
    <el-card shadow="never" class="search-card">
      <el-form
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        label-width="80px"
        class="search-form"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model.number="searchForm.userId"
            placeholder="请输入用户ID"
            clearable
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="活动类型" prop="typeGroup">
          <el-select
            v-model="searchForm.typeGroup"
            placeholder="请选择类型分组"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="(group, key) in typeGroups"
              :key="key"
              :label="group.name"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="操作结果" prop="result">
          <el-select
            v-model="searchForm.result"
            placeholder="请选择结果"
            clearable
            style="width: 120px"
          >
            <el-option label="成功" value="SUCCESS" />
            <el-option label="失败" value="FAILED" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围" prop="timeRange">
          <el-select
            v-model="searchForm.timeRange"
            placeholder="请选择时间范围"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="(name, key) in timeRanges"
              :key="key"
              :label="name"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="IP地址" prop="ipAddress">
          <el-input
            v-model="searchForm.ipAddress"
            placeholder="请输入IP地址"
            clearable
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="关键词" prop="keyword">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索活动描述"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" />
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 高级筛选 -->
      <div class="advanced-filters">
        <el-checkbox v-model="searchForm.importantOnly">
          只显示重要操作
        </el-checkbox>

        <div class="filter-actions">
          <el-button
            type="warning"
            size="small"
            :loading="cleaningExpired"
            @click="handleCleanExpired"
          >
            <IconifyIconOffline icon="ep:delete" />
            清理过期记录
          </el-button>

          <el-button
            type="info"
            size="small"
            :loading="exporting"
            @click="handleExport"
          >
            <IconifyIconOffline icon="ep:download" />
            导出记录
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计信息 -->
    <el-card shadow="never" class="stats-card">
      <div class="stats-row">
        <div class="stat-item">
          <div class="stat-icon total">
            <IconifyIconOffline icon="ep:data-analysis" />
          </div>
          <div class="stat-content">
            <div class="stat-value">
              {{ formatNumber(statistics?.totalActivities || 0) }}
            </div>
            <div class="stat-label">总活动数</div>
          </div>
        </div>

        <div class="stat-item">
          <div class="stat-icon success">
            <IconifyIconOffline icon="ep:check" />
          </div>
          <div class="stat-content">
            <div class="stat-value">
              {{ formatNumber(statistics?.successActivities || 0) }}
            </div>
            <div class="stat-label">成功操作</div>
          </div>
        </div>

        <div class="stat-item">
          <div class="stat-icon failed">
            <IconifyIconOffline icon="ep:close" />
          </div>
          <div class="stat-content">
            <div class="stat-value">
              {{ formatNumber(statistics?.failedActivities || 0) }}
            </div>
            <div class="stat-label">失败操作</div>
          </div>
        </div>

        <div class="stat-item">
          <div class="stat-icon rate">
            <IconifyIconOffline icon="ep:pie-chart" />
          </div>
          <div class="stat-content">
            <div class="stat-value">
              {{ (statistics?.successRate || 0).toFixed(2) }}%
            </div>
            <div class="stat-label">成功率</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 活动记录表格 -->
    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <div class="table-title">
          <h3>活动记录</h3>
          <span class="record-count">共 {{ pagination.total }} 条记录</span>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column
          prop="activityTime"
          label="时间"
          width="160"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.activityTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="userName" label="用户" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <div class="user-name">{{ row.nickName || row.userName }}</div>
              <div class="user-id">ID: {{ row.userId }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="activityType" label="活动类型" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getActivityTagType(row.activityType)"
              size="small"
              effect="light"
            >
              {{ getActivityTypeDisplayName(row.activityType) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="activityDescription"
          label="活动描述"
          min-width="200"
        >
          <template #default="{ row }">
            <div class="activity-description">
              {{ row.activityDescription }}
              <el-tag
                v-if="isImportantActivity(row.activityType)"
                type="warning"
                size="small"
                effect="light"
                class="important-tag"
              >
                重要
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="result" label="结果" width="80">
          <template #default="{ row }">
            <el-tag :type="getActivityResultType(row.result)" size="small">
              {{ row.result === "SUCCESS" ? "成功" : "失败" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="ipAddress" label="IP地址" width="140">
          <template #default="{ row }">
            {{ formatIpAddress(row.ipAddress) }}
          </template>
        </el-table-column>

        <el-table-column prop="userAgent" label="设备信息" width="120">
          <template #default="{ row }">
            {{ formatUserAgent(row.userAgent) }}
          </template>
        </el-table-column>

        <el-table-column label="风险等级" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getRiskLevelType(row.activityType, row.result)"
              size="small"
              effect="light"
            >
              {{ getActivityRiskLevel(row.activityType, row.result).text }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.userId"
              type="primary"
              size="small"
              link
              @click="handleViewUser(row)"
            >
              查看用户
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import {
  getUserActivityListApi,
  getActivityStatisticsApi,
  getActivityTypeGroupsApi,
  getTimeRangeOptionsApi,
  cleanExpiredUserActivitiesApi,
  formatNumber,
  formatIpAddress,
  getActivityTypeDisplayName,
  getActivityResultType,
  isImportantActivity,
  getActivityRiskLevel,
  type UserActivityQuery,
  type UserActivityRecord,
  type ActivityStatistics,
  type ActivityTypeGroups,
  type TimeRangeOptions
} from "@/api/admin-user-profile";

const router = useRouter();

// 响应式数据
const loading = ref(false);
const cleaningExpired = ref(false);
const exporting = ref(false);
const tableData = ref<UserActivityRecord[]>([]);
const statistics = ref<ActivityStatistics | null>(null);
const typeGroups = ref<ActivityTypeGroups>({});
const timeRanges = ref<TimeRangeOptions>({});

// 搜索表单
const searchForm = reactive<UserActivityQuery>({
  userId: undefined,
  typeGroup: "",
  result: "",
  timeRange: "",
  ipAddress: "",
  keyword: "",
  importantOnly: false,
  orderBy: "activityTime",
  orderDirection: "desc",
  page: 1,
  size: 20
});

// 分页信息
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
});

// 方法
const loadActivityList = async () => {
  try {
    loading.value = true;
    const params = {
      ...searchForm,
      page: pagination.current,
      size: pagination.size
    };

    const response = await getUserActivityListApi(params);

    if (response.code === 200) {
      tableData.value = response.data.records;
      pagination.total = response.data.total;
      pagination.current = response.data.current;
      pagination.size = response.data.size;
    } else {
      ElMessage.error(response.message || "获取活动记录失败");
    }
  } catch (error) {
    console.error("加载活动记录失败:", error);
    ElMessage.error("获取活动记录失败");
  } finally {
    loading.value = false;
  }
};

const loadStatistics = async () => {
  try {
    const response = await getActivityStatisticsApi(searchForm.userId, 30);
    if (response.code === 200) {
      statistics.value = response.data;
    }
  } catch (error) {
    console.error("加载统计信息失败:", error);
  }
};

const loadTypeGroups = async () => {
  try {
    const response = await getActivityTypeGroupsApi();
    if (response.code === 200) {
      typeGroups.value = response.data;
    }
  } catch (error) {
    console.error("加载活动类型失败:", error);
  }
};

const loadTimeRanges = async () => {
  try {
    const response = await getTimeRangeOptionsApi();
    if (response.code === 200) {
      timeRanges.value = response.data;
    }
  } catch (error) {
    console.error("加载时间范围失败:", error);
  }
};

const handleSearch = () => {
  pagination.current = 1;
  loadActivityList();
  loadStatistics();
};

const handleReset = () => {
  Object.assign(searchForm, {
    userId: undefined,
    typeGroup: "",
    result: "",
    timeRange: "",
    ipAddress: "",
    keyword: "",
    importantOnly: false,
    orderBy: "activityTime",
    orderDirection: "desc"
  });
  handleSearch();
};

const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
  searchForm.orderBy = prop;
  searchForm.orderDirection = order === "ascending" ? "asc" : "desc";
  loadActivityList();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadActivityList();
};

const handleCurrentChange = (current: number) => {
  pagination.current = current;
  loadActivityList();
};

const handleViewUser = (row: UserActivityRecord) => {
  if (row.userId) {
    router.push(`/system/user/profile/${row.userId}`);
  }
};

const handleCleanExpired = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要清理过期的活动记录吗？此操作不可恢复。",
      "确认清理",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    cleaningExpired.value = true;
    const response = await cleanExpiredUserActivitiesApi();

    if (response.code === 200) {
      ElMessage.success(response.data || "清理完成");
      loadActivityList();
      loadStatistics();
    } else {
      ElMessage.error(response.message || "清理失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("清理过期记录失败:", error);
      ElMessage.error("清理失败");
    }
  } finally {
    cleaningExpired.value = false;
  }
};

const handleExport = async () => {
  try {
    exporting.value = true;
    // TODO: 实现导出功能
    ElMessage.info("导出功能开发中...");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败");
  } finally {
    exporting.value = false;
  }
};

// 工具函数
const formatDateTime = (timeStr: string) => {
  return new Date(timeStr).toLocaleString("zh-CN");
};

const formatUserAgent = (userAgent: string): string => {
  if (!userAgent) return "未知设备";

  if (userAgent.includes("Chrome")) {
    return "Chrome";
  } else if (userAgent.includes("Firefox")) {
    return "Firefox";
  } else if (userAgent.includes("Safari")) {
    return "Safari";
  } else if (userAgent.includes("Edge")) {
    return "Edge";
  } else if (userAgent.includes("Mobile")) {
    return "移动设备";
  } else {
    return "其他";
  }
};

const getActivityTagType = (activityType: string): string => {
  if (activityType.includes("FAILED") || activityType.includes("VIOLATION")) {
    return "danger";
  } else if (isImportantActivity(activityType)) {
    return "warning";
  } else if (
    activityType.includes("LOGIN") ||
    activityType.includes("SUCCESS")
  ) {
    return "success";
  } else {
    return "info";
  }
};

const getRiskLevelType = (activityType: string, result: string): string => {
  const riskLevel = getActivityRiskLevel(activityType, result);
  if (riskLevel.level === "high") return "danger";
  if (riskLevel.level === "medium") return "warning";
  return "success";
};

onMounted(() => {
  loadTypeGroups();
  loadTimeRanges();
  loadActivityList();
  loadStatistics();
});
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 1200px) {
  .user-activity-management {
    .stats-card {
      .stats-row {
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
      }
    }
  }
}

@media (width <= 768px) {
  .user-activity-management {
    padding: 16px;

    .search-form {
      :deep(.el-form-item) {
        width: 100%;
        margin-right: 0;
      }
    }

    .advanced-filters {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }

    .stats-card {
      .stats-row {
        grid-template-columns: 1fr;
        gap: 12px;

        .stat-item {
          padding: 12px;

          .stat-icon {
            width: 40px;
            height: 40px;
            font-size: 16px;
          }

          .stat-content {
            .stat-value {
              font-size: 20px;
            }
          }
        }
      }
    }

    .table-card {
      .table-header {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
      }
    }
  }
}

.user-activity-management {
  min-height: calc(100vh - 84px);
  padding: 20px;
  background-color: #f5f7fa;

  .search-card,
  .stats-card,
  .table-card {
    margin-bottom: 20px;
  }

  .search-form {
    .el-form-item {
      margin-bottom: 16px;
    }
  }

  .advanced-filters {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-top: 16px;
    border-top: 1px solid #e5e7eb;

    .filter-actions {
      display: flex;
      gap: 8px;
    }
  }

  .stats-card {
    .stats-row {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;

      .stat-item {
        display: flex;
        gap: 12px;
        align-items: center;
        padding: 16px;
        background: #f9fafb;
        border: 1px solid #e5e7eb;
        border-radius: 8px;

        .stat-icon {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 48px;
          height: 48px;
          font-size: 20px;
          color: #fff;
          border-radius: 8px;

          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }

          &.success {
            background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
          }

          &.failed {
            background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
          }

          &.rate {
            background: linear-gradient(135deg, #e6a23c 0%, #f0c674 100%);
          }
        }

        .stat-content {
          flex: 1;

          .stat-value {
            font-size: 24px;
            font-weight: 600;
            line-height: 1.2;
            color: #1f2937;
          }

          .stat-label {
            margin-top: 4px;
            font-size: 12px;
            color: #6b7280;
          }
        }
      }
    }
  }

  .table-card {
    .table-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;

      .table-title {
        display: flex;
        gap: 12px;
        align-items: center;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #1f2937;
        }

        .record-count {
          padding: 2px 8px;
          font-size: 12px;
          color: #6b7280;
          background: #f3f4f6;
          border-radius: 12px;
        }
      }
    }

    .user-info {
      .user-name {
        font-weight: 500;
        color: #1f2937;
      }

      .user-id {
        margin-top: 2px;
        font-size: 11px;
        color: #6b7280;
      }
    }

    .activity-description {
      position: relative;

      .important-tag {
        margin-left: 8px;
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}
</style>
